from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from myadmin import models
import random, requests
from django.contrib.auth.hashers import make_password, check_password


# Create your views here.


# 登录页面
def login(request):
    return render(request, 'myhome/login/login.html')


# 执行登录
def dologin(request):
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')

    nextpath = request.GET.get('nextpath')
    if nextpath == '':
        nextpath = '/'

    # 通过手机号获取用户对象
    obj = models.Users.objects.filter(phone=data['phone'])
    if obj.count() == 0:
        return HttpResponse('<script>alert("账户不存在");history.go(-1);</script>')
    # 验证密码
    if check_password(data['password'], obj[0].password):
        # 完成登录操作
        request.session['VipUser'] = {'id': obj[0].id, 'phone': obj[0].phone}
        return HttpResponse(f'<script>alert("欢迎登录");location.href="{nextpath}";</script>')
    else:
        return HttpResponse('<script>alert("密码不正确");history.go(-1);</script>')


# 退出登录
def logout(request):
    # request.session['VipUser'] = ''
    # del request.sessionp['VipUser']
    request.session.flush()
    return HttpResponse(f'<script>alert("退出成功");location.href="/"</script>')


# 注册页面
def register(request):
    return render(request, 'myhome/login/register.html')


# 执行注册操作
def doregister(request):
    data = {}
    data['phone'] = request.POST.get('phone')
    data['password'] = request.POST.get('password')

    # 验证手机验证码是否正确

    # 密码加密
    data['password'] = make_password(data['password'], None, 'pbkdf2_sha256')

    # 存入数据库
    obj = models.Users(**data)
    obj.save()

    return HttpResponse(f'<script>alert("注册成功,欢迎登录");location.href="/login"</script>')


# 手机号注册时的验证
def checkphone(request):
    # 接收
    phone = request.GET.get('phone')
    # 验证
    n = models.Users.objects.filter(phone=phone).count()
    if n:
        return JsonResponse({'code': 1, 'msg': '手机号码已存在'})
    else:
        return JsonResponse({'code': 0, 'msg': '手机号码可用'})


# 给手机号码发送短信验证
def sendphone(request):
    # 接收手机号码
    phone = request.GET.get('phone')

    # 发送短信验证码的api地址
    vcode = random.randint(10000, 99999)
    request.session['vcode'] = {'phone': phone, 'vcode': vcode}
    if SendCode(phone, vcode):
        return JsonResponse({'code': 0, 'msg': '短信验证码已经发送,请查收', 'vcode': vcode})
    else:
        return JsonResponse({'code': 1, 'msg': '短信验证码发送失败', 'vcode': vcode})


def SendCode(phone, vcode):
    # 发送短信验证码的api地址
    url = 'https://open.ucpaas.com/ol/sms/sendsms'
    # 请求是的post数据
    data = {
        "sid": "e730c927adddb1998055b55376f7ae83",
        "token": "68d1fb55958839782fa93e3895302bc0",
        "appid": "f4e85b3fa04343d49193e2d96140eb81",
        "templateid": "522724",
        "param": "87828",
        "mobile": "13470067867"
    }
    headers = {
        'Content-Type': 'application/json'
    }
    # 发送请求
    response = requests.post(url, json=data, headers=headers)
    # 接收响应结果
    res = response.json()
    # 判断当前短信是否发送成功
    if res['code'] == '000000' and res['msg'] == 'OK':
        return True
    else:
        return False
